package com.zll.onlineExam.activities;

import static com.xuexiang.xaop.consts.PermissionConsts.STORAGE;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.LayoutInflaterCompat;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;
import com.mikepenz.iconics.context.IconicsLayoutInflater2;
import com.xuexiang.xaop.annotation.Permission;
import com.xuexiang.xui.widget.edittext.materialedittext.MaterialEditText;
import com.xuexiang.xui.widget.edittext.materialedittext.validation.RegexpValidator;
import com.xuexiang.xui.widget.imageview.RadiusImageView;
import com.xuexiang.xui.widget.imageview.crop.CropImageType;
import com.xuexiang.xui.widget.imageview.crop.CropImageView;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xutil.app.IntentUtils;
import com.xuexiang.xutil.app.PathUtils;
import com.zll.onlineExam.R;
import com.zll.onlineExam.ajax.Ajax;
import com.zll.onlineExam.ajax.HTTPConfig;
import com.zll.onlineExam.ajax.ReqCallback;
import com.zll.onlineExam.entity.out.UserDtoOut;
import com.zll.onlineExam.utils.BitmapUtil;
import com.zll.onlineExam.utils.GlobalDataHolder;
import com.zll.onlineExam.utils.XToastUtils;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.HashMap;
import java.util.Map;

public class AccountSettingActivity extends AppCompatActivity implements View.OnClickListener {

    private RadiusImageView mUserHead;
    private LinearLayout mEditMask;
    private SuperButton mBtnRotate;
    private SuperButton mBtnCrop;
    private MaterialEditText mNickname;
    private MaterialEditText mEmail;
    private MaterialEditText mDescription;
    private CropImageView mEditImage;
    private ImageView mBack;
    private ImageView mCommit;

    private boolean editMode;

    private final int FILE_SUCCESS = 1;
    private final int FILE_FAIL = 0;
    private final int FILE_ERROR = -1;
    private final int COMMIT_SUCCESS = 4;
    private final int COMMIT_FAIL = 3;
    private final int COMMIT_ERROR = 2;
    private final int REQUEST_IMAGE = 2220;

    private static Handler mHandler;
    private static DataHolder mHolder;
    private static final String TAG = "===AccountSetting";

    private Map<String,Object> userInfo ;

    private final static String namePattern = "^[\\u4E00-\\u9FA5A-Za-z0-9_]{4,15}$";
    private final static String descPattern = "^[\\u4E00-\\u9FA5A-Za-z0-9_]{0,40}$";
    private final static String emailPattern = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";

    private class DataHolder{
        String fileName;
        Bitmap avatar;

        public String getFileName() {
            return fileName;
        }

        public DataHolder setFileName(String fileName) {
            this.fileName = fileName;
            return this;
        }

        public Bitmap getAvatar() {
            return avatar;
        }

        public DataHolder setAvatar(Bitmap avatar) {
            this.avatar = avatar;
            return this;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LayoutInflaterCompat.setFactory2(getLayoutInflater(), new IconicsLayoutInflater2(getDelegate()));
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_setting);

        initView();
        initListener();
        initHandler();
        initData();



    }

    private void initView() {
        mUserHead = findViewById(R.id.riv_info_head_pic);
        mEditMask = findViewById(R.id.edit_mask);
        mBtnRotate = findViewById(R.id.btn_info_rotate);
        mBtnCrop = findViewById(R.id.btn_info_crop);
        mNickname = findViewById(R.id.a_info_nickname);
        mEmail = findViewById(R.id.a_info_email);
        mDescription = findViewById(R.id.a_info_description);
        mBack = findViewById(R.id.iv_back);
        mCommit = findViewById(R.id.iv_commit);
        mEditImage = findViewById(R.id.crop_image_view);

        mEditImage.setFixedAspectRatio(true);
        mEditImage.setAspectRatio(1,1);
        mEditImage.setGuidelines(CropImageType.CROPIMAGE_GRID_ON);

    }

    private void initListener() {
        mBack.setOnClickListener(this);
        mCommit.setOnClickListener(this);
        mUserHead.setOnClickListener(this);
        mBtnRotate.setOnClickListener(this);
        mBtnCrop.setOnClickListener(this);

        mNickname.addValidator(new RegexpValidator("格式不对",namePattern));
        mEmail.addValidator(new RegexpValidator("格式不对",emailPattern));
        mDescription.addValidator(new RegexpValidator("格式不对",descPattern));

        ImageOptions imageOptions = new ImageOptions.Builder()
                // 如果ImageView的大小不是定义为wrap_content, 不要crop.
                .setCrop(true) // 很多时候设置了合适的scaleType也不需要它.
                // 加载中或错误图片的ScaleType
                //.setPlaceholderScaleType(ImageView.ScaleType.MATRIX)
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setPlaceholderScaleType(ImageView.ScaleType.CENTER_CROP)
                .setLoadingDrawableId(R.drawable.ic_default_head)
                .setFailureDrawableId(R.drawable.ic_default_head)
                .setIgnoreGif(false)
                .build();
        x.image().bind(mUserHead, GlobalDataHolder.getInstance().getCurUser().getAvatar(HTTPConfig.API+HTTPConfig.IMG_PREFIX),imageOptions);
    }

    private void initHandler() {
        mHandler = new Handler(){
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                mCommit.setEnabled(true);
                switch (msg.what) {
                    case FILE_SUCCESS:
                        userInfo.put("avatar",mHolder.getFileName());
                        mUserHead.setImageBitmap(mHolder.getAvatar());
                        cancelEdit();
                        break;
                    case COMMIT_SUCCESS:
                        XToastUtils.success("提交成功");
                        finish();
                        break;
                    case FILE_FAIL:
                        XToastUtils.error("头像上传失败");
                        break;
                    case FILE_ERROR:
                        XToastUtils.error("网络异常");
                        break;
                    case COMMIT_FAIL:
                        XToastUtils.error("提交失败");
                        break;
                    case COMMIT_ERROR:
                        XToastUtils.error("网络异常");
                        break;
                    default:
                        break;
                }

            }
        };
    }

    private void initData() {
        userInfo = new HashMap<>();
        userInfo.put("uid", GlobalDataHolder.getInstance().getCurUser().getUid());

        mNickname.setText(GlobalDataHolder.getInstance().getCurUser().getNickname());
        mEmail.setText(GlobalDataHolder.getInstance().getCurUser().getEmail());
        mDescription.setText(GlobalDataHolder.getInstance().getCurUser().getDescription());

        mHolder = new DataHolder();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back){
            finish();
        }
        if (id == R.id.iv_commit){
            commitInfos();
        }
        if (id == R.id.riv_info_head_pic){
            editMode = !editMode;
            if (editMode){
                selectImage();
            }else{
                cancelEdit();
            }
        }
        if (id == R.id.btn_info_rotate){
            mEditImage.rotateImage(90);
        }
        if (id == R.id.btn_info_crop){
            mEditImage.cropImage();
            Bitmap croppedImage = mEditImage.getCroppedImage();
            if (croppedImage == null){
                XToastUtils.error("裁剪图片失败,请重试");
                return;
            }
            Bitmap cropBitmap = BitmapUtil.cropBitmap(croppedImage, 200, 200);
            commitAvatar(cropBitmap);
        }
    }

    private void commitInfos() {
        if (mNickname.validate() && mEmail.validate() && mDescription.validate() && mEmail.getEditValue().length() <= 40){
            userInfo.put("nickname",mNickname.getEditValue());
            userInfo.put("email",mEmail.getEditValue());
            userInfo.put("description",mDescription.getEditValue());

            XToastUtils.info("正在提交，请稍候");

            Ajax.post(HTTPConfig.CHANGE_INFO, userInfo, new ReqCallback() {
                @Override
                public void onSuccess(JSONObject resp) {
                    GlobalDataHolder.getInstance().setCurUser(resp.getObject("data", UserDtoOut.class));
                    mHandler.sendEmptyMessage(COMMIT_SUCCESS);
                }

                @Override
                public void onFail(String msg) {
                    mHandler.sendEmptyMessage(COMMIT_FAIL);
                }

                @Override
                public void onError(String msg) {
                    mHandler.sendEmptyMessage(COMMIT_ERROR);
                }
            });
        }else{
            XToastUtils.error("请先填写信息");
        }
    }

    private void commitAvatar(Bitmap cropBitmap) {
        if (cropBitmap == null){
            XToastUtils.error("获取图片失败");
            return;
        }
        mHolder.setAvatar(cropBitmap);

        String avatarStr = BitmapUtil.BitmapToBase64(cropBitmap);
        Map<String,Object> map = new HashMap<>();
        map.put("base64File",avatarStr);
        Log.d(TAG, "commitAvatar: "+avatarStr);
        Ajax.post(HTTPConfig.SAVE_FILE, map, new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                mHandler.sendEmptyMessage(FILE_SUCCESS);
                mHolder.setFileName(resp.getJSONObject("data").getString("fileName"));
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(FILE_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(FILE_ERROR);
            }
        });

    }

    private void cancelEdit() {
        editMode = false;
        mEditMask.setVisibility(View.GONE);
    }

    @Permission(STORAGE)
    private void selectImage() {
        startActivityForResult(IntentUtils.getDocumentPickerIntent(IntentUtils.DocumentType.IMAGE), REQUEST_IMAGE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择系统图片并解析
        if (requestCode == REQUEST_IMAGE && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    Log.d(TAG, "onActivityResult: "+uri);
                    Log.d(TAG, "onActivityResult: "+PathUtils.getFilePathByUri(uri));
                    mEditImage.setImagePath(PathUtils.getFilePathByUri(uri));
                    mBtnRotate.setEnabled(true);
                    mBtnCrop.setEnabled(true);
                    mEditMask.setVisibility(View.VISIBLE);
                }
            }
        }
    }
}